package my.webservices;

import static my.audit.message.beans.AuditEvent.ADD_VEH_HISTORY;

import java.sql.Timestamp;
import java.util.Date;

import my.audit.message.beans.Audit;
import my.webservices.beans.AddVehicleHistoryResponse;
import my.webservices.beans.Vehicle;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.jms.core.JmsTemplate;

@Aspect
public class VehicleAuditAdvisor {

	private JmsTemplate jmsTemplate;
	
	@AfterReturning(pointcut="execution(* my.webservices.VehicleHistoryService.addVehicleHistory(..))", returning="response")
	public void addAudit(AddVehicleHistoryResponse response) {
			Audit audit = create(response.getVehicle());
			send(audit);
	}
	
	private Audit create(Vehicle veh){
		Audit audit = new Audit();
		audit.setEvent(ADD_VEH_HISTORY);
		audit.setDate(new Timestamp(new Date().getTime()));
		audit.setUser("SYSTEM");
		StringBuffer details = new StringBuffer("Vehicle # :");
		details.append(veh.getVehicleNumber()).append(" having vin#:").append(veh.getVin()).append(" added successfully.");
		details.append(" Following history also added: ").append(veh.getHistory());
		audit.setDetails(details.toString());
		return audit;
	}
	
	private void send(Audit audit){
		jmsTemplate.convertAndSend(audit);
	}

	/**
	 * @param jmsTemplate the jmsTemplate to set
	 */
	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

}
